package functions

import (
	"fmt"

	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/coerce"

	"github.com/project-flogo/core/data/expression/function"
)

func init() {
	err := function.Register(&fnKvToArray{})
	if err != nil {
		panic(err)
	}
}

type fnKvToArray struct{}

func (fnKvToArray) Name() string {
	return "kvToArray"
}

func (fnKvToArray) Sig() (paramsTypes []data.Type, isVariadic bool) {
	return []data.Type{data.TypeObject}, false
}

func (fnKvToArray) Eval(params ...interface{}) (interface{}, error) {
	m, err := coerce.ToObject(params[0])
	if err != nil {
		return nil, fmt.Errorf("kvToArray function parameter [%+v] must be map", params[0])
	}
	array := []map[string]interface{}{}
	for k, v := range m {
		pair := map[string]interface{}{
			"key":   k,
			"value": v,
		}
		array = append(array, pair)
	}
	return array, nil
}
